import tkinter as tk
from tkinter import ttk
import pandas as pd
import os
class TableApp:
    def __init__(self, root):
        self.root = root
        self.root.title("增删改查")
        self.root.geometry("600x400")

        # 设置ttk主题
        style = ttk.Style(root)
        style.theme_use('clam')  # 可以选择 'clam', 'alt', 'default', 'classic' 等
        style.configure('TButton', font=('Helvetica', 12), foreground='blue')
        style.configure('Red.TButton', font=('Helvetica', 12), foreground='red') # 红色按钮
        style.configure('TLabel', font=('Helvetica', 12), foreground='black')
        style.configure('TEntry', font=('Helvetica', 12))
        
        # 创建一个DataFrame来存储数据
        self.data = pd.DataFrame(columns=['Name', 'Age', 'Gender'])

        # 创建表格
        self.tree = ttk.Treeview(root, columns=('Name', 'Age', 'Gender'), show='headings')
        self.tree.heading('Name', text='Name')
        self.tree.heading('Age', text='Age')
        self.tree.heading('Gender', text='Gender')
        self.tree.grid(row=0, column=0, columnspan=4, padx=10, pady=10, sticky="nsew")

        # 绑定选中事件
        self.tree.bind('<<TreeviewSelect>>', self.on_tree_select)

        # 创建输入框
        self.name_var = tk.StringVar()
        self.age_var = tk.StringVar()
        self.gender_var = tk.StringVar()

        ttk.Label(root, text="Name").grid(row=1, column=0, padx=10, pady=5, sticky="w")
        self.name_entry = ttk.Entry(root, textvariable=self.name_var)
        self.name_entry.grid(row=1, column=1, padx=10, pady=5, sticky="w")

        ttk.Label(root, text="Age").grid(row=2, column=0, padx=10, pady=5, sticky="w")
        self.age_entry = ttk.Entry(root, textvariable=self.age_var)
        self.age_entry.grid(row=2, column=1, padx=10, pady=5, sticky="w")

        ttk.Label(root, text="Gender").grid(row=3, column=0, padx=10, pady=5, sticky="w")
        self.gender_entry = ttk.Entry(root, textvariable=self.gender_var)
        self.gender_entry.grid(row=3, column=1, padx=10, pady=5, sticky="w")

        # 创建按钮
        self.add_button = ttk.Button(root, text="Add", command=self.add_item)
        self.add_button.grid(row=4, column=0, padx=10, pady=10, sticky="w")

        self.update_button = ttk.Button(root, text="Update", command=self.update_item)
        self.update_button.grid(row=4, column=1, padx=10, pady=10, sticky="w")

        self.delete_button = ttk.Button(root, text="Delete", command=self.delete_item)
        self.delete_button.grid(row=4, column=2, padx=10, pady=10, sticky="w")
        
        self.save_button = ttk.Button(root, text="Save",style='Red.TButton', command=self.save_item)
        self.save_button.grid(row=4, column=3, padx=10, pady=10, sticky="w")

        # 配置列和行的权重
        root.columnconfigure(0, weight=1)
        root.columnconfigure(1, weight=1)
        root.columnconfigure(2, weight=1)
        root.columnconfigure(3, weight=1)
        root.rowconfigure(0, weight=1)

        self.load_data()
    
    # 默认选中行
    def selectRow(self,row=0):
        items = self.tree.get_children()    
        if items :
            self.tree.selection_set(items[row])
    
    # 选中行后的回调函数
    def on_tree_select(self, event):
        selecteditems = self.tree.selection()  # 获取选中的行
        if selecteditems: 
            values = self.tree.item(selecteditems[0], 'values')  # 获取选中行的值
            self.name_var.set(values[0])
            self.age_var.set(values[1])
            self.gender_var.set(values[2])

    # 加载数据
    def load_data(self):
        if os.path.exists('data.csv'):
            self.data = pd.read_csv('data.csv') 
        for index, row in self.data.iterrows():
            self.tree.insert('', 'end', values=(row['Name'], row['Age'], row['Gender']))
        self.selectRow()
    
    # 保存数据到 csv
    def save_item(self):
        self.data.to_csv('data.csv', index=False) # 测试 保存数据到 csv 文件
        
    # 添加一行
    def add_item(self):
        name = self.name_var.get()
        age = self.age_var.get()
        gender = self.gender_var.get()
        new_row = pd.DataFrame({'Name': [name], 'Age': [age], 'Gender': [gender]})
        self.data = pd.concat([self.data, new_row], ignore_index=True)
        self.tree.insert('', 'end', values=(name, age, gender))

    # 更新选中的行
    def update_item(self):
        selected_item = self.tree.selection()
        if selected_item:
            name = self.name_var.get()
            age = self.age_var.get()
            gender = self.gender_var.get()
            self.tree.item(selected_item, values=(name, age, gender))
            index = self.tree.index(selected_item)
            self.data.at[index, 'Name'] = name
            self.data.at[index, 'Age'] = age
            self.data.at[index, 'Gender'] = gender

    # 删除选中的行
    def delete_item(self):
        selected_item = self.tree.selection()
        if selected_item:
            index = self.tree.index(selected_item)
            self.tree.delete(selected_item)
            self.data.drop(index, inplace=True)
            self.data.reset_index(drop=True, inplace=True)
            if index < len(self.data):
                self.selectRow(index)
            else:
                self.selectRow(len(self.data)-1)

if __name__ == "__main__":
    root = tk.Tk()
    app = TableApp(root)
    root.mainloop()
